<template>
  <el-dialog
    top="30px"
    width="900px"
    class="dialog-sm"
    append-to-body
    :before-close="beforeClose"
    :close-on-click-modal="false"
    :title="dialogTitle"
    :visible.sync="visible"
  >
    <el-form
      :model="editCustomerData"
      v-loading="loading"
      label-position="left"
      size="small"
      :rules="rules"
      ref="form"
      label-width="150px"
      class="project-form"
    >
      <h4 class="form-title">基本信息</h4>
      <el-form-item label="组织类型" prop="org_class">
        <select-customer-type
          class="form-control-ml"
          v-model="editCustomerData.org_class"
          @select="handleOrgClassSelect"
        ></select-customer-type>
      </el-form-item>

      <el-form-item
        label="营业执照OCR识别(请上传清晰的图片，以确保识别准确性，非必填)"
        v-show="isCommon"
      >
        <upload-oss
          single-image
          :dir="dir"
          ref="uploadRegister"
          accept="image/*"
          :fileName="0"
          :file-list="registerList"
          :on-change="registerChange"
          :on-complete="handleUploadRegister"
        ></upload-oss>
      </el-form-item>

      <el-form-item label="身份证照片OCR识别(请上传清晰的图片，以确保识别准确性，非必填)">
        <ul class="list-inline">
          <li class="list-inline-item">
            <upload-oss
              single-image
              :dir="dir"
              ref="uploadFront"
              accept="image/*"
              :fileName="0"
              :file-list="idImgFront"
              :on-change="idImgFrontChange"
              :on-complete="handleUploadFront"
            ></upload-oss>
            <div class="text-muted text-center">身份证头像页</div>
          </li>
          <li class="list-inline-item">
            <upload-oss
              single-image
              :dir="dir"
              ref="uploadBack"
              accept="image/*"
              :file-list="idImgBack"
              :on-complete="handleUploadBack"
            ></upload-oss>
            <div class="text-muted text-center">身份证国徽页</div>
          </li>
        </ul>
      </el-form-item>

      <el-form-item label="客户名称" prop="customer_name">
        <el-autocomplete
          v-model="editCustomerData.customer_name"
          class="form-control-ml"
          placeholder="请输入客户名称"
          popper-class="customer-autocomplete"
          value-key="customer_name"
          :fetch-suggestions="throttleGetData"
          @input="clearId"
          @select="handleSelectFarm"
        >
          <template slot-scope="props">
            <div class="farm-name">{{ props.item.customer_name || '' }}</div>
            <small class="text-muted">
              {{ (props.item.address || '') + (props.item.address_detail || '') }}
            </small>
          </template>
        </el-autocomplete>
      </el-form-item>
      <!-- <el-form-item label="组织类型" prop="org_class">
        <select-farm-org
          v-model="editCustomerData.org_class"
          class="form-control-ml"
          @select="handleOrgClassSelect"
        ></select-farm-org>
      </el-form-item> -->

      <el-form-item :label="isCommon ? '经营地址' : '家庭地址'" prop="address_code">
        <select-address
          class="form-control-ml"
          @select="getAddress"
          clearable
          v-model="editCustomerData.address_code"
          auto-top
        ></select-address>
      </el-form-item>
      <el-form-item label="详细地址(街道、门牌)">
        <el-input
          v-model="editCustomerData.address_detail"
          class="form-control-ml"
          placeholder="请勿重复输入已选地址（对已选地址的补充说明）"
        ></el-input>
        <div class="text-warning small form-control-ml" style="line-height: 1.2">
          请勿重复输入已选地址,当前地址：
          {{
            addressLabel
              ? topAddressLabel + addressLabel + editCustomerData.address_detail
              : tableData.address
          }}
        </div>
      </el-form-item>

      <el-form-item label="营业执照号" v-if="isCommon" prop="register_no">
        <el-input
          v-model="editCustomerData.register_no"
          class="form-control-ml"
          placeholder="营业执照号"
        >
          <el-button slot="append" class="input-group-text" type="info" @click="linkto">
            工商信息
          </el-button>
        </el-input>
      </el-form-item>

      <el-form-item label="成立日期" v-if="isCommon">
        <el-input
          v-model="editCustomerData.established_date"
          class="form-control-ml"
          placeholder="成立日期"
        ></el-input>
      </el-form-item>

      <el-form-item label="注册资本" v-if="isCommon">
        <el-input
          v-model="editCustomerData.register_funds"
          class="form-control-ml"
          placeholder="注册资本"
        ></el-input>
      </el-form-item>

      <el-form-item label="营业期限" v-if="isCommon">
        <el-input
          v-model="editCustomerData.bussiness_years"
          class="form-control-ml"
          placeholder="营业期限"
        ></el-input>
      </el-form-item>

      <el-form-item label="营业执照证件地址" v-if="isCommon">
        <el-input
          v-model="editCustomerData.cert_address"
          class="form-control-ml"
          placeholder="营业执照证件地址"
        ></el-input>
      </el-form-item>

      <el-form-item label="负责人" prop="corp_name" v-if="isCommon">
        <el-input
          v-model="editCustomerData.corp_name"
          class="form-control-ml"
          placeholder="请输入负责人名称"
        ></el-input>
      </el-form-item>
      <el-form-item :label="isCommon ? '负责人身份证' : '证件号码'" prop="lender_idcard">
        <el-input
          v-model="editCustomerData.lender_idcard"
          class="form-control-ml"
          placeholder="请输入身份证号"
        >
          <!-- <el-button slot="append" class="input-group-text" type="info" @click="linkto">
            <i class="fa fa-camera"></i>
            OCR
          </el-button> -->
        </el-input>
      </el-form-item>
      <el-form-item label="身份证证件地址">
        <el-input
          v-model="editCustomerData.cert_address_corp"
          class="form-control-ml"
          placeholder="身份证证件地址"
        ></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="mobile_no">
        <el-input
          v-model="editCustomerData.mobile_no"
          class="form-control-ml"
          placeholder="请输入联系电话"
        ></el-input>
      </el-form-item>

      <el-form-item label="经营范围" prop="business_scope">
        <el-input
          type="textarea"
          :rows="3"
          v-model="editCustomerData.business_scope"
          class="form-control-ml"
          placeholder="请输入经营范围"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否扶贫项目">
        <el-radio v-model="editCustomerData.is_poverty_project" label="1">是</el-radio>
        <el-radio v-model="editCustomerData.is_poverty_project" label="0">否</el-radio>
      </el-form-item>

      <el-form-item :label="povertyLabel" prop="poverty_households">
        <el-input
          v-model="editCustomerData.poverty_households"
          class="form-control-ml"
          :placeholder="`请输入${povertyLabel}数量`"
        >
          <span slot="append">人</span>
        </el-input>
      </el-form-item>

      <h4 class="form-title">贷款信息</h4>

      <el-form-item label="申请金额" prop="apply_funds">
        <el-input
          v-model="editCustomerData.apply_funds"
          class="form-control-ml"
          placeholder="请输入申请金额"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>

      <el-form-item label="贷款年限" prop="load_years">
        <el-input
          v-model="editCustomerData.load_years"
          class="form-control-ml"
          placeholder="请输入贷款年限"
        >
          <span slot="append">年</span>
        </el-input>
      </el-form-item>

      <el-form-item label="贷款实际用途" prop="funds_use_dir">
        <el-input
          v-model="editCustomerData.funds_use_dir"
          class="form-control-ml"
          placeholder="请输入贷款实际用途"
        ></el-input>
      </el-form-item>

      <el-form-item label="是否有共同借款人">
        <el-radio v-model="editCustomerData.is_comm_loan" label="1">是</el-radio>
        <el-radio v-model="editCustomerData.is_comm_loan" label="0">否</el-radio>
      </el-form-item>
      <template v-if="+editCustomerData.is_comm_loan === 1">
        <el-form-item label="共同借款人">
          <el-button size="mini" @click="addPerson">
            <i class="fa fa-plus"></i>
            新增共同借款人
          </el-button>
          <table
            style="line-height: 1.2rem"
            class="table table-bordered table-sm bg-white table-vertical-middle text-center"
          >
            <colgroup>
              <col width="12%" />
              <col width="15%" />
              <col width="12%" />
              <col width="16%" />
              <col width="20%" />
              <col width="15%" />
              <col width="10%" />
            </colgroup>
            <tr>
              <td>类型</td>
              <td>主体名称</td>
              <td>法人名字</td>
              <td>联系电话</td>
              <td>证件号</td>
              <td>地址</td>
              <td>操作</td>
            </tr>
            <tr v-for="(p, index) of personData" :key="index">
              <td>{{ enumEntityType[p.com_person_type] }}</td>
              <td>{{ p.person_name }}</td>
              <td>{{ +p.com_person_type === 1 ? p.person_name_corp : '-' }}</td>
              <td>{{ p.person_phone }}</td>
              <td>{{ p.cert_no }}</td>
              <td>{{ p.person_address }}</td>
              <td>
                <el-button type="text" @click="addPerson(p, index)">
                  <i class="fa fa-edit"></i>
                </el-button>
                <el-button type="text" @click="deletePerson(index)">
                  <i class="fa fa-trash text-danger"></i>
                </el-button>
              </td>
            </tr>
            <tr v-if="!personData.length">
              <td colspan="7" class="text-muted">请先新增共同借款人</td>
            </tr>
          </table>
        </el-form-item>
      </template>

      <template v-if="!isNeedType">
        <h4 class="form-title">担保信息</h4>
        <template>
          <el-form-item label="业务模式" prop="is_pro_dir" v-if="isUnion">
            <c-select
              :options="enumIsPro"
              v-model="editCustomerData.is_pro_dir"
              placeholder="请选择业务模式"
              class="form-control-ml"
            ></c-select>
          </el-form-item>
          <el-form-item label="业务模式" prop="gua_type" v-else>
            <select-gua-type
              placeholder="请选择业务模式"
              @select="onSelectGuaType"
              v-model="editCustomerData.gua_type"
              class="form-control-ml"
            ></select-gua-type>
          </el-form-item>

          <el-form-item
            label="联保机构"
            prop="gua_service_id"
            v-if="isUnionType"
            :rules="{
              required: true,
              message: '请选择联保机构',
              trigger: 'change',
            }"
          >
            <select-org-credit
              v-model="editCustomerData.gua_service_id"
              @select="handleAccessAgencyChange"
              class="form-control-ml"
              placeholder="请选择担保机构"
            ></select-org-credit>
          </el-form-item>
        </template>

        <el-form-item
          label="项目行业分类"
          prop="ind_class_code"
          v-if="isUnion || +editCustomerData.gua_type === 4"
        >
          <select-parent-main
            placeholder="请选择行业分类"
            class="form-control-ml"
            v-model="editCustomerData.ind_class_code"
            @select="handleSelectIndClass"
          ></select-parent-main>
        </el-form-item>

        <!-- 2021.6.1 合并十二大产业分类和项目行业分类，不能统计则不统计 -->
        <!-- 2021.9.18 直担，国家分类与十二大产品分开选，国家分类包含所有类型（包含非农业） -->

        <template v-else>
          <el-form-item label="行业分类" prop="parent_main_business_code">
            <select-industrial-class
              filterable
              class="form-control-ml"
              v-model="editCustomerData.parent_main_business_code"
              @select="selectIndustrial"
              placeholder="请选择行业分类"
            ></select-industrial-class>
          </el-form-item>

          <el-form-item label="是否为十二大产业" prop="is_ind12">
            <el-radio-group v-model="editCustomerData.is_ind12">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="十二大产业分类"
            prop="main_business"
            v-if="+editCustomerData.is_ind12 === 1"
          >
            <select-main-business
              class="form-control-ml"
              v-model="editCustomerData.main_business"
              placeholder="请选择十二大产业分类"
            ></select-main-business>
          </el-form-item>
        </template>

        <el-form-item
          label="贷款具体用途"
          prop="use_category"
          v-if="isUnion || +editCustomerData.gua_type === 4"
        >
          <select-funds-user
            v-model="editCustomerData.use_category"
            :parent-id="editCustomerData.ind_class_code || ''"
            @select="setUserLabel"
            class="form-control-ml"
            placeholder="请输入贷款具体用途"
          ></select-funds-user>
        </el-form-item>

        <el-form-item label="项目负责人: A角" prop="res_a">
          <select-staff
            :isDefaultDept="+editCustomerData.gua_type === 4"
            v-model="editCustomerData.res_a"
            ref="resA"
            class="form-control-ml"
            placeholder="请选择项目负责人: A角"
          ></select-staff>
        </el-form-item>
        <el-form-item label="项目负责人: B角" prop="res_b">
          <select-staff
            :isDefaultDept="+editCustomerData.gua_type === 4"
            v-model="editCustomerData.res_b"
            ref="resB"
            class="form-control-ml"
            placeholder="请选择项目负责人: B角"
          ></select-staff>
        </el-form-item>

        <el-form-item label="产品选择" prop="project_type_id">
          <select-credit-product
            placeholder="请选择担保产品（非必填）"
            class="form-control-ml"
            clearable
            v-model="editCustomerData.project_type_id"
            @change="setLoanMode"
            :project-type="editCustomerData.gua_type"
          ></select-credit-product>
        </el-form-item>

        <el-form-item label="指定银行">
          <select-org-bank
            v-model="editCustomerData.bank_id"
            :project-type="editCustomerData.gua_type"
            placeholder="选择指定银行（非必填）"
            @select="setPublicName"
            filterable
            clearable
            class="form-control-ml"
          ></select-org-bank>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button type="primary" :loading="saveLoading" class="btn-long" @click="submitForm">
          {{ hasRefuse ? '受理' : '保存' }}
        </el-button>
        <el-button
          type="danger"
          v-if="hasRefuse"
          :loading="saveLoading"
          class="btn-long"
          @click="handleRefuse"
        >
          拒绝
        </el-button>
      </el-form-item>
    </el-form>
    <common-person
      :visible.sync="editCommonVisible"
      :form-data="editCommonForm"
      @back="setPerson"
      :attach="editPersonAttach"
    ></common-person>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { throttle } from '@vimi/utils-tool'
import { idCardValidator, mobileValidator, registerNoValidator } from '@/common/plugins/validator'
// import { createFarm, putFarm } from '@/common/api/industrial'

import SelectAddress from '@/components/select/SelectAddress'
import SelectStaff from '@/components/select/SelectStaff'
// import SelectFarmOrg from '@/components/select/SelectFarmOrg'
import SelectOrgBank from '@/credit/components/select/SelectOrgBank'
import SelectGuaType from '@/credit/components/select/SelectGuaType.vue'
import SelectOrgCredit from '@/credit/views/county/unionProvince/components/item/SelectCredit'
import SelectCreditProduct from '@/credit/components/select/SelectCreditProduct'
import SelectParentMain from '@/bank/views/limit/SelectParentMain.vue'
import SelectFundsUser from '@/bank/views/limit/SelectFundsUser.vue'
import { enumEntityType } from '@/credit/views/county/unionProvince/components/ContractGuardMortgage'

import SelectIndustrialClass from '@/credit/components/select/SelectIndustrialClass.vue'
import SelectMainBusiness from '@/credit/components/select/SelectMainBusiness.vue'
import SelectCustomerType from '@/components/select/SelectCustomerType'
import {
  getIdCard,
  getOrgInfo,
  ocrDateFormat,
  OCR_LICENSE_PERIOD_LONG,
} from '@/credit/views/city/program/ocr/index'
import CommonPerson from '@/credit/views/city/program/ocr/CommonPerson'
import { uploadOss, deleteOss } from '@/common/api/oss'
import { addressFromLevel } from '@vimi/utils-tool'
export const enumChannelType = {
  0: '常规业务',
  1: '便捷业务',
}
//
export const enumIsPro = {
  0: '联担业务',
  1: '直担业务',
}
export default {
  components: {
    // SelectFarmOrg,
    SelectAddress,
    SelectOrgBank,
    SelectStaff,
    SelectGuaType,
    SelectOrgCredit,
    SelectCreditProduct,
    SelectParentMain,
    SelectFundsUser,
    SelectIndustrialClass,
    SelectMainBusiness,
    SelectCustomerType,
    CommonPerson,
  },
  props: {
    visible: Boolean,
    customerRelatedId: String,
    projectType: {
      type: String,
      default: '1',
    },
    isNeedType: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    hasRefuse: { type: Boolean, default: false },
  },
  data() {
    const isNumberValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!Number.isFinite(+value)) {
        callback(new Error('请输入正确的数值'))
      } else {
        callback()
      }
    }

    const isEqPersonValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (this.editCustomerData.res_b === this.editCustomerData.res_a) {
        callback(new Error('项目A角与项目B角不能为同一个人'))
      } else {
        callback()
      }
    }

    const classValidator = (rule, value, callback) => {
      const data = this.enumOrgClass.find(item => item.orgClass === value) || {}
      if (!value) {
        callback()
      } else if (+data.busType === 2 && +this.editCustomerData.gua_type === 4) {
        callback(new Error('联担业务不支持当前组织类型'))
      } else {
        callback()
      }
    }

    return {
      enumEntityType,
      enumIsPro,
      customerParams: {
        index: 1,
        size: 30,
        'submit_type.eq': 2,
        customer_name: '',
        address_code: '',
      },
      tableName: 'customer_related',
      publicId: null,
      editCustomerData: {
        customer_name: '',
        corp_name: '',
        lender_idcard: '',
        address_code: '',
        bank_id: '',
        bank_type: '',
        bank_name: '',
        address_detail: '',
        org_class: '',
        mobile_no: '',
        apply_funds: '',
        register_no: '',
        poverty_households: '',
        business_scope: '',
        load_years: '',
        funds_use_dir: '',
        gua_type: '',
        res_a: '',
        res_b: '',
        submit_type: '',
        main_business: '',

        is_poverty_project: '0',
        project_type_id: '',
        project_type_name: '',
        is_agr_related: '0',
        ind_class_code: '',
        ind_class_name: '',
        // channel_type: '0'
        use_category: '',
        is_comm_loan: '0',
        // diy key
        is_ind12: '0', // 是否为十二大产业
        cert_address: '',
        cert_address_corp: '',
        register_funds: '',
        established_date: '',
        bussiness_years: '',
        is_pro_dir: '0',
        gua_service_name: '',
        gua_service_id: '',
        parent_main_business: '',
        parent_main_business_code: '',
      },
      // initCustomerData: {},
      rules: {
        customer_name: [
          { required: true, message: '请输入客户名称', trigger: 'blur' },
          { required: true, message: '请输入客户名称', trigger: 'change' },
        ],
        corp_name: { required: true, message: '请输入负责人名字', trigger: 'blur' },
        lender_idcard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: idCardValidator, message: '身份证号格式错误', trigger: 'blur' },
        ],
        register_no: [
          { required: true, message: '请输入营业执照号', trigger: 'blur' },
          {
            validator: registerNoValidator,
            message: '营业执照号格式错误',
            trigger: 'blur',
          },
        ],
        address_code: { required: true, message: '请选择经营地址', trigger: 'change' },
        org_class: [
          { required: true, message: '请选择组织类型', trigger: 'change' },
          { validator: classValidator, trigger: 'blur' },
        ],
        mobile_no: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: mobileValidator, message: '手机号码错误', trigger: 'blur' },
        ],
        apply_funds: [
          { required: true, message: '请输入申请金额', trigger: 'blur' },
          { validator: isNumberValidator, trigger: 'blur' },
        ],
        load_years: [
          { required: true, message: '请输入贷款年限', trigger: 'blur' },
          { validator: isNumberValidator, trigger: 'blur' },
        ],
        funds_use_dir: { required: true, message: '请输入贷款用途', trigger: 'blur' },
        use_category: { required: true, message: '请选择贷款具体用途', trigger: 'change' },
        gua_type: { required: true, message: '请选择业务模式', trigger: 'change' },
        is_pro_dir: { required: true, message: '请选择业务模式', trigger: 'change' },
        // channel_type: { required: true, message: '请选择业务通道', trigger: 'change' },
        res_a: [
          { required: true, message: '请选择A角', trigger: 'change' },
          { validator: isEqPersonValidator, trigger: 'change' },
        ],
        res_b: [
          { required: true, message: '请选择B角', trigger: 'change' },
          { validator: isEqPersonValidator, trigger: 'change' },
        ],
        is_ind12: { required: true, message: '请选择是否为十二大产业', trigger: 'change' },
        main_business: { required: true, message: '请选择十二大产业分类', trigger: 'change' },
        parent_main_business_code: {
          required: true,
          message: '请选择行业分类',
          trigger: 'change',
        },
        ind_class_code: { required: true, message: '请选择项目行业类型', trigger: 'change' },
        poverty_households: { validator: isNumberValidator, trigger: 'blur' },
      },
      saveLoading: false,
      tableData: {},
      loading: false,
      isCommon: false,
      tableListName: 'comm_loan_person',
      personData: [],
      mainPerson: [],
      addressLabel: '',
      idImgFront: [],
      idImgBack: [],
      registerList: [],
      imgData: [],
      attachTable: 'datum_customer_attachment',
      attachAll: [],
      deleteAttach: [],

      editCommonVisible: false,
      editCommonForm: {},

      editIndex: '-1',
      commonOcr: {},
      attachs: {},
      editPersonAttach: [],
      bolbUrl: {},
      topAddressLabel: '',
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user', 'org', 'enumOrgClass']),
    queryAddressCode() {
      return this.user.queryAddressCode
    },
    isUnion() {
      return this.user?.scopeArr?.includes('dirGuaPro') ?? false
    },
    type() {
      return !this.customerRelatedId
    },
    dialogTitle() {
      return this.title || `${this.type ? '新增' : '修改'}项目`
    },

    // 是否已经立项（受理后业务类型不能修改）
    isApprovaled() {
      return +this.tableData.item_status > 0
    },

    // 是否需要选择联保机构
    isUnionType() {
      return (
        +this.editCustomerData.is_pro_dir === 0 &&
        +this.editCustomerData.gua_type !== 2 &&
        this.isUnion
      )
    },

    // 是否涉农
    isAgr() {
      return +this.editCustomerData.is_agr_related === 1
    },
    povertyLabel() {
      return this.isAgr ? '带动农户' : '带动就业'
    },
    dir() {
      return `credit/newProjec/${this.editCustomerData.lender_idcard}`
    },
    orgClass() {
      return this.user.clientOrgClass
    },
    isBank() {
      return this.orgClass === 'org_bank'
    },
  },
  watch: {
    customerRelatedId: {
      handler: function () {
        this.bolbUrl = {}
        this.commonOcr = {}
        this.personData = []
        this.mainPerson = []
        if (this.customerRelatedId) {
          this.getData()
        } else {
          this.tableData = {}
          this.idImgFront = []
          this.idImgBack = []
          this.registerList = []
          this.setCustomerData(this.tableData)
        }
      },
      immediate: true,
    },
    visible() {
      this.initAttach(this.attachAll)
    },
  },
  mounted() {},
  created() {
    this.customerParams['service_id.eq'] = this.clientId
    this.getAddressData()
  },
  methods: {
    getAddressData() {
      const address = new Set()

      address.add(addressFromLevel(this.queryAddressCode, 1))
      address.add(addressFromLevel(this.queryAddressCode, 2))
      address.add(addressFromLevel(this.queryAddressCode, 3))
      if (!this.queryAddressCode) {
        this.topAddressLabel = ''
        return
      }
      this.$api
        .getData(
          'industrial_db',
          'geo_codings',
          {
            'orWhere.id.eq': [...address],
          },
          { region_lever: 'asc' }
        )
        .then(res => {
          const data = res?.data ?? []
          this.topAddressLabel = data.map(item => item.geo_name).join('')
        })
    },
    selectIndustrial(v, l) {
      this.editCustomerData.parent_main_business = l?.ind_class_name ?? ''
    },
    setPerson(person, file) {
      this.commonOcr[person.cert_no] = file
      const url = file ? URL.createObjectURL(file) : ''
      if (this.bolbUrl[person.cert_no]) {
        URL.revokeObjectURL(this.bolbUrl[person.cert_no][0].url)
      }
      this.bolbUrl[person.cert_no] = [{ url: url }]
      if (this.editIndex === -1) {
        this.personData.push(person)
      } else {
        this.personData[this.editIndex] = { ...person }
      }
    },
    uploadCommonFile() {
      for (let key in this.bolbUrl) {
        URL.revokeObjectURL(this.bolbUrl[key][0].url)
      }
      this.imgData = []
      const uploadFiles = []
      const urls = []
      Object.keys(this.commonOcr).forEach(key => {
        if (this.attachs[key]) {
          this.deleteAttach.push(this.attachs[key]?.[0])
          urls.push(this.attachs[key]?.[0]?.url)
        }
        const data = this.personData.find(item => key === item.cert_no)
        if (data) {
          uploadFiles.push({
            com_person_type: data.com_person_type,
            cert_no: data.cert_no,
            file: this.commonOcr[data.cert_no],
            person_name: data.person_name,
          })
        }
      })
      if (!uploadFiles.length || +this.editCustomerData.is_comm_loan === 0) {
        return Promise.resolve({})
      }
      const promises = uploadFiles.map(it =>
        uploadOss({
          file: it.file,
          dir: `credit/newProjec/common/${it.cert_no}`,
          type: 0,
        })
      )
      return Promise.all(promises).then(list => {
        list.forEach((url, index) => {
          const { com_person_type, person_name, cert_no } = uploadFiles[index]
          const data = {
            attachment: url,
            parent_attachment_type: '立项附件',
            attachment_type: +com_person_type === 1 ? '营业执照' : '身份证',
            file_type: 1,
            attachment_type_code: 'face',
            lender_idcard: cert_no,
            remark: `共同借款人-${person_name}`,
          }
          if (this.customerRelatedId) {
            data.customer_related_id = this.customerRelatedId
          }
          this.imgData.push(data)
        })
        deleteOss(urls)
      })
    },
    submitAttachment() {
      if (this.imgData.length > 0) {
        this.$api.addBatch('credit', 'datum_customer_attachment', this.imgData).catch(err => {
          this.$message.error(err?.data?.error_description || '附件保存失败，请重试！')
        })
      }
    },
    handleUploadAttach(img, fileUrl, type = '身份证', isFase = true, id, fileName = '') {
      if (img.url && img.url !== fileUrl.url) {
        const data = {
          attachment: img.url,
          attachment_type: type,
          parent_attachment_type: '立项附件',
          attachment_type_code: isFase ? 'face' : 'back',
          lender_idcard: id,
          remark: fileName || img.name,
        }
        if (this.customerRelatedId) {
          data.customer_related_id = this.customerRelatedId
        }
        this.imgData.push(data)
        if (fileUrl.id) {
          this.deleteAttach.push(fileUrl)
        }
      }
    },
    handleUploadRegister(images) {
      const img = images?.[images.length - 1] || {}
      const fileUrl = this.registerList?.[0] || {}
      this.handleUploadAttach(
        img,
        fileUrl,
        '营业执照',
        true,
        this.editCustomerData.register_no,
        `营业执照-${this.editCustomerData.customer_name}`
      )
      this.onSubmit()
    },
    registerChange(file) {
      if (!file || !file.raw) {
        return
      }
      const fileData = file.raw
      this.loading = true
      getOrgInfo(fileData)
        .then(res => {
          const data = res?.data ?? {}
          this.editCustomerData.register_no = data.reg_num || ''
          this.editCustomerData.corp_name = data.person
          this.editCustomerData.customer_name = data.name
          this.editCustomerData.cert_address = data.address
          this.editCustomerData.business_scope = data.business
          this.editCustomerData.register_funds = data.capital
          this.editCustomerData.established_date = ocrDateFormat(data.establish_date)
          this.editCustomerData.bussiness_years =
            data.valid_period === OCR_LICENSE_PERIOD_LONG
              ? '长期'
              : `${this.editCustomerData.established_date}至${ocrDateFormat(data.valid_period)}`
        })
        .finally(() => {
          this.loading = false
        })
    },
    async idImgFrontChange(file) {
      if (!file || !file.raw) {
        return
      }
      const fileData = file.raw
      this.loading = true
      getIdCard(fileData, true)
        .then(res => {
          const data = res?.data ?? {}
          this.editCustomerData.lender_idcard = data.num || ''
          this.editCustomerData.corp_name = data.name
          this.editCustomerData.cert_address_corp = data.address
          if (!this.isCommon) {
            this.editCustomerData.customer_name = data.name
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleUploadFront(images) {
      const img = images?.[images.length - 1] || {}
      const fileUrl = this.idImgFront?.[0] || {}
      const name = this.isCommon
        ? `身份证(头像页)-${this.editCustomerData.corp_name}`
        : `身份证(头像页)-${this.editCustomerData.customer_name}`
      this.handleUploadAttach(
        img,
        fileUrl,
        '身份证',
        true,
        this.editCustomerData.lender_idcard,
        name
      )
      this.$refs.uploadBack.submit()
    },
    handleUploadBack(images) {
      const img = images?.[images.length - 1] || {}
      const fileUrl = this.idImgBack?.[0] || {}
      const name = this.isCommon
        ? `身份证(国徽页)-${this.editCustomerData.corp_name}`
        : `身份证(国徽页)-${this.editCustomerData.customer_name}`
      this.handleUploadAttach(
        img,
        fileUrl,
        '身份证',
        false,
        this.editCustomerData.lender_idcard,
        name
      )
      this.$refs.uploadRegister.submit()
    },
    getAddress(label) {
      this.addressLabel = label || ''
    },
    deletePerson(index) {
      if (this.personData.length < 2) {
        return this.$message.warning('最少需添加一个共同借款人')
      }
      this.personData.splice(index, 1)
    },
    addPerson(row = {}, index = -1) {
      if (row.cert_no) {
        this.editPersonAttach = this.bolbUrl[row.cert_no] || this.attachs[row.cert_no] || []
      } else {
        this.editPersonAttach = []
      }
      this.editCommonVisible = true
      this.editCommonForm = { ...row }
      this.editIndex = index
    },
    handleRefuse() {
      if (!this.customerRelatedId) {
        return
      }
      this.$prompt('请输入拒绝理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入不通过原因' : true),
      })
        .then(({ value }) => {
          this.saveLoading = true
          this.$api
            .updateData(this.$serviceName, 'customer_related', this.customerRelatedId, {
              confuse_status: 3,
              confuse_time: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
              confuse_person: this.user.realName,
              confuse_des: value,
              is_approval: 2,
              approved_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
            })
            .then(() => {
              this.beforeClose()
              this.$emit('success', true)
              this.$message.success('项目已拒绝')
            })
            .catch(() => {
              this.$message.error(`项目拒绝失败，请重试`)
            })
            .finally(() => {
              this.saveLoading = false
            })
        })
        .catch(() => {})
    },
    onSelectGuaType() {
      this.editCustomerData.project_type_id = ''
      this.editCustomerData.bank_id = ''
      this.editCustomerData.bank_name = ''
      this.editCustomerData.res_a = ''
      this.editCustomerData.res_b = ''
      this.$refs.form.clearValidate()
    },
    throttleGetData: throttle(500, function (queryString, cb) {
      this.getCustomer(queryString, cb)
    }),
    getAttachMent() {
      return this.$utils.promise(
        this.$api.getData('credit', this.attachTable, {
          'customer_related_id.eq': this.customerRelatedId,
          'attachment_type.in': '身份证,营业执照',
        })
      )
    },
    setPublicName(bank) {
      this.editCustomerData.bank_type = bank.agency_type_sub || ''
      this.editCustomerData.bank_name = bank.agency_name || ''
    },
    async getData() {
      // 通过传入的customer_related_id获取到客户信息
      const params = { 'customer_related_id.eq': this.customerRelatedId }
      this.loading = true
      const [res, err] = await this.$utils.promise(
        this.$api.getData('credit', this.tableName, params)
      )
      const [person, err1] = await this.$utils.promise(
        this.$api.getData('credit', this.tableListName, params)
      )
      const [attach, err2] = await this.getAttachMent()

      this.loading = false

      if (err || err1 || err2) {
        return this.$message.error('获取客户信息失败！')
      }
      this.attachAll = attach?.data || []
      const data = (res && res.data && res.data.length && res.data[0]) || {}
      const personData = person?.data ?? []
      this.mainPerson = personData.filter(item => +item.is_main === 1)
      this.personData = personData.filter(item => +item.is_main === 0)

      this.tableData = data
      this.setCustomerData(data)
      this.initAttach(attach.data ?? [])
    },
    initAttach(attach) {
      this.attachs = attach.reduce((ob, item) => {
        ob[item.lender_idcard] = [{ url: item.attachment, id: item.id }]
        return ob
      }, {})
      const customerIdCardFace = attach.find(
        item =>
          item.attachment_type === '身份证' &&
          item.attachment_type_code === 'face' &&
          item.lender_idcard === this.editCustomerData.lender_idcard
      )
      if (customerIdCardFace) {
        this.idImgFront = [{ url: customerIdCardFace.attachment, id: customerIdCardFace.id }]
      } else {
        this.idImgFront = []
      }
      const customerIdCardBack = attach.find(
        item =>
          item.attachment_type === '身份证' &&
          item.attachment_type_code === 'back' &&
          item.lender_idcard === this.editCustomerData.lender_idcard
      )
      if (customerIdCardBack) {
        this.idImgBack = [{ url: customerIdCardBack.attachment, id: customerIdCardBack.id }]
      } else {
        this.idImgBack = []
      }
      const customerRegitster = attach.find(
        item =>
          item.attachment_type === '营业执照' &&
          item.lender_idcard === this.editCustomerData.register_no
      )
      if (customerRegitster) {
        this.registerList = [{ url: customerRegitster.attachment, id: customerRegitster.id }]
      } else {
        this.registerList = []
      }
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.saveLoading = true
          this.uploadCommonFile().finally(() => {
            this.saveLoading = false
            this.$refs.uploadFront.submit()
          })
        } else {
          this.$message.warning('填写的数据有误，请检查填写内容')
        }
      })
    },
    onSubmit() {
      const { editCustomerData, isNeedType } = this
      const data = {
        customer_name: editCustomerData.customer_name,
        corp_name: this.isCommon ? editCustomerData.corp_name : editCustomerData.customer_name,
        customer_type: this.isCommon ? 1 : 2,
        mobile_no: editCustomerData.mobile_no,
        address_code: editCustomerData.address_code,
        address_detail: editCustomerData.address_detail,
        register_no: this.isCommon ? editCustomerData.register_no : '',
        org_class: editCustomerData.org_class,
        org_class_name: editCustomerData.org_class_name,
        lender_idcard: editCustomerData.lender_idcard,
        project_type: this.projectType,
        poverty_households: editCustomerData.poverty_households,
        business_scope: editCustomerData.business_scope,
        res_a: editCustomerData.res_a,
        res_b: editCustomerData.res_b,
        res_a_name: (this.$refs.resA && this.$refs.resA.getSelectedName()) || '',
        res_b_name: (this.$refs.resB && this.$refs.resB.getSelectedName()) || '',
        submit_type: 2,

        main_business: editCustomerData.main_business,
        parent_main_business_code: editCustomerData.parent_main_business_code || '',
        parent_main_business: editCustomerData.parent_main_business || '',
        is_poverty_project: editCustomerData.is_poverty_project,
        bank_id: editCustomerData.bank_id || '',
        bank_name: editCustomerData.bank_name,
        bank_type: editCustomerData.bank_type,
        apply_funds: editCustomerData.apply_funds,
        load_years: editCustomerData.load_years,
        funds_use_dir: editCustomerData.funds_use_dir,
        project_type_id: editCustomerData.project_type_id,
        project_type_name: editCustomerData.project_type_name,
        ind_class_code: editCustomerData.ind_class_code,
        ind_class_name: editCustomerData.ind_class_name,
        is_approval: isNeedType ? 0 : 1,
        channel_type: 0,
        recommend_status: 1,
        use_category: editCustomerData.use_category,
        use_category_name: editCustomerData.use_category_name,
        is_comm_loan: editCustomerData.is_comm_loan,
        cert_address: editCustomerData.cert_address,
        cert_address_corp: editCustomerData.cert_address_corp,
        register_funds: editCustomerData.register_funds,
        established_date: editCustomerData.established_date,
        bussiness_years: editCustomerData.bussiness_years,
        is_pro_dir: editCustomerData.is_pro_dir,
        gua_service_name: this.isUnionType ? editCustomerData.gua_service_name : '',
        gua_service_id: this.isUnionType ? editCustomerData.gua_service_id : '',
        is_ind12: editCustomerData.is_ind12,
      }
      if (this.isBank) {
        data.bank_id = this.clientId
        data.bank_name = this.org.orgName
      } else {
        data.service_id = this.clientId
        data.service_name = this.org.orgName
      }
      if (editCustomerData.gua_type) {
        data.gua_type = editCustomerData.gua_type
      }
      if (editCustomerData.customer_id) {
        data.customer_id = editCustomerData.customer_id
      }
      data.submit_person_name = this.user.realName
      data.submit_client_id = this.clientId
      data.submit_client_name = this.org.orgName
      if (!isNeedType) {
        data.approved_date = this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')
      }

      if (+this.editCustomerData.is_comm_loan === 1 && this.personData.length < 1) {
        return this.$message.error('至少输入一个共同借款主体')
      }
      const personData = [...this.personData]
      const mainPerson = {
        com_person_type: this.isCommon ? 1 : 2,
        person_name: this.editCustomerData.customer_name,
        person_phone: this.editCustomerData.mobile_no,
        is_main: 1,
        cert_no: this.isCommon
          ? this.editCustomerData.register_no
          : this.editCustomerData.lender_idcard,
        person_address: this.addressLabel
          ? this.addressLabel + this.editCustomerData.address_detail
          : this.tableData.address,
      }
      personData.push(mainPerson)

      if (this.customerRelatedId) {
        data.customer_related_id = this.customerRelatedId
      }

      const addformData = {
        masterTableInfo: JSON.stringify(data),
        masterTableName: this.tableName,
        slaveTableInfo: JSON.stringify(personData),
        slaveTableName: this.tableListName,
        slaveTableName1: this.attachTable,
        slaveTableInfo1: JSON.stringify(this.imgData),
      }
      const updateformData = {
        masterTableInfo: JSON.stringify(data),
        masterTableName: this.tableName,
        slaveTableInfo: JSON.stringify(personData),
        slaveTableName: this.tableListName,
      }

      if (!this.customerRelatedId) {
        this.addFarm(addformData)
      } else {
        // 修改需传所有附件不然会删除，所以单独添加附件
        this.updateFarm(updateformData)
        this.submitAttachment()
      }
    },
    updateFarm(data) {
      this.saveLoading = true
      this.$api
        .relatedUpdate(this.$serviceName, data)
        .then(() => {
          this.$message.success('操作成功！')
          this.handleSuccess()
          this.getData()
          this.deleteAttachMent()
        })
        .catch(err => {
          if (err) {
            const errStr =
              typeof err.data?.error_description === 'string'
                ? err.data?.error_description
                : '操作失败，请重试！'
            return this.$message.error(`${errStr}`)
          }
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    deleteAttachMent() {
      if (!this.deleteAttach.length) {
        return
      }
      const ids = this.deleteAttach.map(item => item.id).join(',')
      // 组件自带删除fileList oss文件
      // const urls = this.deleteAttach.map(item => item.url)
      this.$api.deleteData(this.$serviceName, this.attachTable, ids)
      // deleteOss(urls)
      this.deleteAttach = []
    },
    addFarm(data) {
      this.saveLoading = true
      this.$api
        .relatedBatch(this.$serviceName, data)
        .then(() => {
          this.$message.success('添加客户成功！')
          this.handleSuccess()
        })
        .catch(err => {
          if (err) {
            const errStr =
              typeof err.data?.error_description === 'string'
                ? err.data?.error_description
                : '添加客户失败，请重试！'
            return this.$message.error(`${errStr}`)
          }
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    handleSuccess() {
      this.idImgFront = []
      this.idImgBack = []
      this.registerList = []
      this.beforeClose()
      this.$emit('success', true)
      this.tableData = {}
      this.setCustomerData(this.tableData)
    },
    beforeClose() {
      this.setCustomerData(this.tableData)
      this.addressLabel = ''
      this.$emit('update:visible', false)
    },
    handleSelectFarm(customer) {
      this.setCustomerData(customer)
    },

    handleAccessAgencyChange(agency) {
      this.editCustomerData.gua_service_name = agency?.agency_name || ''
    },

    setCustomerData(customer) {
      Object.keys(this.editCustomerData).forEach(key => {
        this.editCustomerData[key] = customer[key] || ''
      })
      this.editCustomerData.lender_idcard = customer.id_card || customer.lender_idcard
      this.editCustomerData.customer_id = customer.customer_id
      this.editCustomerData.gua_type = customer.gua_type || ''

      if (!this.editCustomerData.is_poverty_project) {
        this.editCustomerData.is_poverty_project = '0'
      }
      if (!this.editCustomerData.is_comm_loan) {
        this.editCustomerData.is_comm_loan = '0'
      }

      if (!this.editCustomerData.is_pro_dir) {
        this.editCustomerData.is_pro_dir = '0'
      }
      if (!this.editCustomerData.is_ind12) {
        this.editCustomerData.is_ind12 = '1'
      }

      if (this.isUnion) {
        // this.editCustomerData.is_pro_dir = '0'
        this.editCustomerData.gua_type = '4'
      }

      this.isCommon = +customer.customer_type === 1
      this.tableData.address = customer.address || '' // 共同借款人地址

      this.$nextTick(() => {
        this.$refs.form?.clearValidate()
      })
    },
    clearId() {
      if (this.customerRelatedId) {
        return
      }
      this.editCustomerData.customer_id = ''
    },
    async getCustomer(queryString = '', cb) {
      queryString = queryString.trim()
      let data = []

      if (this.customerParams.customer_name === queryString) {
        cb(data)
        return
      }

      this.customerParams.customer_name = queryString
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'datum_customer_info_warehouse', this.customerParams)
      )

      if (res && res.data) {
        data = res.data.data || []
      }

      cb(data)
    },
    linkto() {
      window.open('http://www.gsxt.gov.cn/index.html')
    },
    setLoanMode(_, select) {
      this.editCustomerData.project_type_name = select.load_name || ''
    },
    handleSelectIndClass(_, select) {
      // this.editCustomerData.is_agr_related = select.is_agr_related || '0'
      // this.editCustomerData.main_business = select.main_business || ''
      // this.editCustomerData.parent_main_business_code = select.parent_main_business_code || ''
      this.editCustomerData.use_category = ''
      this.editCustomerData.ind_class_name = select.value || ''
    },
    setUserLabel(select) {
      this.editCustomerData.use_category_name = select.value || ''
    },
    handleOrgClassSelect(val, item) {
      if (!item) return
      this.isCommon = +item.customerType === 1
      this.editCustomerData.org_class_name = item.orgClassName
    },
  },
}
</script>
<style lang="scss" scoped>
.form-title {
  font-size: 1.15rem;
  color: $gray-600;
  margin: 2rem 0 1rem 0;

  &:first-child {
    margin-top: 0;
  }
}
.project-form .el-form-item {
  margin-left: 1.5rem;
}
.input-td {
  background: #ffffee;
}
</style>
